<?php
// +----------------------------------------------------------------------
// | 海豚PHP框架 [ DolphinPHP ]
// +----------------------------------------------------------------------
// | 版权所有 2016~2019 广东卓锐软件有限公司 [ http://www.zrthink.com ]
// +----------------------------------------------------------------------
// | 官方网站: http://dolphinphp.com
// +----------------------------------------------------------------------

namespace app\member\admin;

use app\admin\controller\Admin;
use app\common\builder\ZBuilder;
use app\member\model\Member as MemberModel;
use think\Db;

/**
 * 菜单控制器
 * @package app\cms\admin
 */
class Index extends Admin
{
    /**
     * 菜单列表
     * @param null $id 导航id
     * @author 蔡伟明 <314013107@qq.com>
     * @return mixed
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function index()
    {
        cookie('__forward__', $_SERVER['REQUEST_URI']);
        // 查询
        $map = $this->getMap();
        $list_rows1 = input('list_rows');
        $listRows = isset($list_rows1)?$list_rows1:10;
        if ($this->request->isPost()) {
            $data = $this->request->post();
        }
        
        if(empty($map['deal_date'][1][0])){
            $beginday=date('Y-m-d',time()-2592000);//30天前
        }else{
            $beginday=date('Y-m-d',strtotime($map['deal_date'][1][0]));
        }
        if(empty($map['deal_date'][1][1])){
            $endday=date('Y-m-d',time());
        }else{
            $endday=date('Y-m-d',strtotime($map['deal_date'][1][1]));
        }
        
        // 获取排序
        $order = $this->getOrder();
        if(empty($order)){
            $order='user_id desc';
        }
        
//         $data_list = MemberModel::view('member a', true)
//             ->view('member_info b','real_name,idcard,head_img','a.user_id=b.uid','left')
//             ->paginate($listRows)         //添加数据
//             ->each( function($item, $key){
//                 $mobile=db('members')->where('id',$item->recommend_id)->value('user_name');
//                 $item->recommend_tel=($mobile)?$mobile:'';
//             });
        
        $data_list = MemberModel::where($map)->order($order)->paginate();
        
        // 使用ZBuilder快速创建数据表格
        if(empty($_SERVER["QUERY_STRING"])){
            $excel_url=substr(http().$_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"],0,-5)."_export";
        }else{
            $excel_url=substr(http().$_SERVER["SERVER_NAME"].$_SERVER["PHP_SELF"],0,-5)."_export.html?".$_SERVER["QUERY_STRING"];
        }
        $btn_excel = [
            'title' => '导出EXCEL表',
            'icon'  => 'fa fa-fw fa-download',
            'href'  => url($excel_url,'','')
        ];
                
        $source_arr=getFilterarr('member','source');                 //来源去重数组
        $address_arr=getFilterarr('member','address');                 //微信地址去重数组
        
        return   ZBuilder::make('table')
        ->setPageTitle('会员列表') // 设置页面标题
        ->setTableName('member') // 设置数据表名
        ->addOrder('user_id,mobile,car_nums,hits,c_time') // 添加排序
        ->addFilterList('sex',['0'=>'未选择','1'=>'男','2'=>'女'])
        ->addFilterList('user_type',['0'=>'普通游客','1'=>'高级会员'])
        ->addFilterList('source',$source_arr)
        ->addFilterList('address',$address_arr)
        ->addTimeFilter('c_time', [$beginday, $endday]) // 添加时间段筛选
        ->setSearch(['nick_name' => '昵称','mobile'=>'会员电话','real_name'=>'真实姓名','ip'=>'注册IP','wx_openid'=>'微信ID']) // 设置搜索参数
        ->addTopButton('custom',$btn_excel)
        ->addColumns([ // 批量添加列
            ['user_id', 'ID','callback',function($v){
                return '<a href="javascrip:void(0)">'.$v.'</a>';
            },'','seltc_member_id'],
            ['wx_openid', '微信id'],
            ['nick_name','会员昵称'],
            ['mobile','手机号码'],
            ['sex','会员性别','callback',function($v){
                return ($v=='0')?'未选择':(($v=='1')?'男':'女');
            }],
            ['address', '微信地址'],
            ['source', '来源'],
            ['hits', '来访次数'],
            ['c_time', '注册时间','datetime'],
            ['ip', '注册IP'],
            ['user_type','会员类型','callback',function($v){
                return ($v=='0')?'普通游客':'高级会员';
            }],
            ['status', '是否冻结', 'switch'],
//             ['right_button', '操作', 'btn']
        ])
        ->hideCheckbox()
        ->setPrimaryKey('user_id')
        ->setColumnWidth('user_id', 80)
        ->setColumnWidth('user_name,real_name,source,mobile', 120)
        ->setColumnWidth('c_time,ip', 150)
        ->setColumnWidth('wx_openid', 300)
//         ->addRightButton('edit')
//         ->addRightButton('custom', [
//             'title' => '新增银行卡',
//             'icon'  => 'fa fa-fw fa-cc-paypal',
//             'href'  => url('add', ['uid' => '__id__'])
//         ]) 
        ->setRowList($data_list) // 设置表格数据
        ->js('admin_memberclick','admin')
        ->fetch(); // 渲染页面
    }
    
    
    /**
     * 会员导出功能
     */
    public function index_export(){
        //添加用户导出记录
        action_log('index_export', 'members', 1, UID, '管理员执行了用户导出的操作!');
        
        // 获取查询条件
        $map = $this->getMap();
        
        // 获取排序
        $order = $this->getOrder();
        if(empty($order)){
            $order='user_id desc';
        }
        // 数据列表
        $xlsData = MemberModel::view('member', true)
        ->where($map)->order($order)
        ->select()         //添加数据
        ->each( function($item, $key){
            $item->sex=($item->sex=='0')?'未选择':($item->sex='1'?'男':'女');
            $item->c_time=date('Y-m-d H:i',$item->c_time);
        })->toArray();
        

        $title="用户信息列表";
        $arrHeader = array('用户ID','昵称','手机号','会员性别','微信IP','微信地址','来源','注册IP','注册时间','来访次数');
        $fields = array('user_id','nick_name','mobile','sex','wx_openid','address','source','ip','c_time','hits');
        exportExcel($arrHeader,$fields,$xlsData,$title);
        
    }
    
    
    
    /**
     * 快速编辑
     */
    public function quickedit($record = []){
        if ($this->request->isPost()) {
            $data = $this->request->post();
            if(!UID){
                $this->error('禁止操作当前账号');
            }
            $id      = trim($data['pk']);
            $field   = trim($data['name']);
            $value   = (isset($data['value']) && trim($data['value'])=='true')?'1':'0';
            MemberModel::where('user_id', $id)->update([$field=>$value]);       //修改用户冻结信息
            
            // 记录行为
            $djstatus=($value)?'冻结':'正常';
            action_log('index_quickedit', 'members', $id, UID, '会员'.$id.'的冻结状态改为'.$djstatus);
            $this->success('编辑成功', cookie('__forward__'));
        }
    }
    

    /**
     * 会员详情
     */
    public function info(){
        // 保存数据
        if ($this->request->isPost()) {
            $data = $this->request->post();
            if(!isset($data['user_id']) || empty($data['user_id'])){
                return myjson('0','用户ID不能为空！');
            }
            $reg=db('member')->where('user_id',trim($data['user_id']))->update(['user_type'=>trim($data['user_type']),'remark'=>trim($data['remark'])]);
            if(!$reg){
                return myjson('0','没有内容被修改！');
            }
            return myjson('1','修改成功！');
        }else{
            $id=$_REQUEST['id'];
            if(is_numeric($id)){
                $useinfo=db('member')->where('user_id',$id)->find();
                if(is_array($useinfo) && count($useinfo)>0){
                    $useinfo['sex_show']=($useinfo['sex']=='0'?'未选择':($useinfo['sex']=='1'?'男':'女'));
                    $useinfo['c_time_show']=date('Y-m-d H:s',$useinfo['c_time']);
                    $useinfo['u_time_show']=date('Y-m-d H:s',$useinfo['u_time']);
                    $this->assign('useinfo',$useinfo);
                    
                    //用户登录记录
                    $logininfo=db('member_login')->where('uid',$id)->limit(10)->order('add_time desc')->select();
                    if(is_array($logininfo) && count($logininfo)>0){
                        foreach ($logininfo as $key=>&$hang){
                            $logininfo[$key]['add_time_show']=date('Y-m-d H:i',$hang['add_time']);
                        }
                        unset($hang);
                        $this->assign('logininfo',$logininfo);
                    }
                }
            }
            
            return $this->fetch();
        }
    }
    
    
    ///用户登录记录
    public function getuserloginip(){
        $uid=$_REQUEST['id'];
        $page=(isset($_REQUEST['page'])&&!empty($_REQUEST['page']))?$_REQUEST['page']:1;
        $limit=(isset($_REQUEST['limit'])&&!empty($_REQUEST['limit']))?$_REQUEST['limit']:10;

        //用户登录记录
        $logininfo=Db::name('member_login')->where('uid',$uid)->order('add_time desc')->paginate_page($limit,$page);
        
        if(is_array($logininfo['data']) && count($logininfo['data'])>0){
            foreach ($logininfo['data'] as $key=>&$hang){
                $logininfo['data'][$key]['add_time_show']=date('Y-m-d H:i',$hang['add_time']);
            }
            unset($hang);
           
            return myjson(1,$logininfo);
        }else{
            return myjson(0,"暂无数据");
        }
    }

    //短信日志
    public function telsendlog(){
        cookie('__forward__', $_SERVER['REQUEST_URI']);
        // 查询
        $map = $this->getMap();
        $list_rows1 = input('list_rows');
        $listRows = isset($list_rows1)?$list_rows1:10;
        if ($this->request->isPost()) {
            $data = $this->request->post();
        }
        // 获取排序
        $order = $this->getOrder();
        if(empty($order)){
            $order='id desc';
        }

        $data_list = Db::name('telsendlog')->where($map)->order($order)->paginate($listRows);         //添加数据
        
        return   ZBuilder::make('table')
        ->setPageTitle('会员短信发送记录') // 设置页面标题
        ->setTableName('telsendlog') // 设置数据表名
        ->addOrder('id,sendtime') // 添加排序
        ->setSearch(['mobile'=>'手机号']) // 设置搜索参数
        ->addColumns([ // 批量添加列
            ['id', 'ID'],
            ['mobile', '短信号码'],
            ['sendtime', '发送时间','callback',function($v){
                return date('Y-m-d H:i:s',$v);
            }],
            ['info', '短信内容'],
//             ['ip', '发送IP'],
//             ['ref', '发送来源'],
            
        ])
        ->hideCheckbox()
        ->setRowList($data_list) // 设置表格数据
        ->setColumnWidth('mobile', 120)
        ->setColumnWidth('sendtime', 180)
        ->setColumnWidth('info', 300)
        ->fetch(); // 渲染页面
    }
  
    
}